package com.htfyun.ft.fragment.factory;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.net.ConnectivityManager;
import android.net.Network;
import android.net.NetworkCapabilities;
import android.net.NetworkInfo;
import android.net.NetworkRequest;
import android.net.Uri;
import android.os.Bundle;
import android.os.PersistableBundle;
import android.os.StatFs;
import android.os.storage.StorageVolume;
import android.view.View;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.htfyun.ft.R;
import com.htfyun.ft.common.SDCardInfo;
import com.htfyun.ft.utils.DebugLog;

import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;


public class FragmentTypeC extends FactoryBaseFragment {

    //    private final static String ACTION_HDMI_PLUGGED = "android.intent.action.HDMI_PLUGGED";
    private final static String ACTION_DP_PLUGGED = "android.intent.action.DP_PLUGGED";
    //    private final static String EXTRA_HDMI_PLUGGED_STATE = "state";
    private final static String EXTRA_DP_PLUGGED_STATE = "state";

    private final static String U_STORAGE_PATH_NAME = "sdc";

    private TextView txtStatusHdmi;
    private TextView txtStatusEthernet;
    private TextView txtStatusUStorage;

    private TextView txtInfo;

    private List<TextView> textViewList = new ArrayList<>();

    private final int COLOR_OK = Color.GREEN;

    @Override
    protected int getLayoutRes() {
        return R.layout.fragment_factory_type_c;
    }

    @Override
    protected void onInitView(@Nullable Bundle savedInstanceState) {
        super.onInitView(savedInstanceState);
        txtStatusHdmi = (TextView) findViewById(R.id.txtStatusHdmi);
        txtStatusEthernet = (TextView) findViewById(R.id.txtStatusEthernet);
        txtStatusUStorage = (TextView) findViewById(R.id.txtStatusUStorage);
        txtInfo = (TextView) findViewById(R.id.txtInfo);

        txtStatusHdmi.setTag(R.string.type_c_hdmi_status);
        txtStatusEthernet.setTag(R.string.type_c_ethernet_status);
        txtStatusUStorage.setTag(R.string.type_c_ustorage_status);

        setBtnPassVisibility(View.GONE);
    }

    private void initWhenVisible() {

        txtInfo.setText("");

        textViewList.clear();
        textViewList.add(txtStatusHdmi);
        textViewList.add(txtStatusEthernet);
        textViewList.add(txtStatusUStorage);

        for (TextView txt : textViewList) {
            String statusUnplugged = getString(R.string.type_c_status_unplugged);
            if ((txt.getTag() instanceof Integer)) {
                int resId = (Integer) txt.getTag();
                txt.setText(getString(resId, statusUnplugged));
            }
            txt.setBackgroundColor(Color.LTGRAY);
        }
    }

    @Override
    protected void onVisible() {
        super.onVisible();

        initWhenVisible();

        synchronized (FragmentTypeC.class) {
            registerHdmi();
            registerEthernet();
            registerUStorage();
        }
    }

    @Override
    protected void onInvisible() {
        super.onInvisible();
        synchronized (FragmentTypeC.class) {
            unregisterHdmi();
            unregisterEthernet();
            unregisterUStorage();
        }
    }

    private void setTxtStatusPlugged(TextView textView) {
        String statusPlugged = getString(R.string.type_c_status_plugged);

        Object tag = textView.getTag();
        if (tag == null) {
            return;
        }
        if (!(tag instanceof Integer)) {
            return;
        }
        int resId = (Integer) tag;

        textView.setText(getString(resId, statusPlugged));
        textView.setBackgroundColor(COLOR_OK);

        textViewList.remove(textView);

        if (textViewList.isEmpty()) {
            delayAutoPass();
        }

    }

    ///////
    // hdmi
    private boolean isHdmiRegistered = false;

    private void registerHdmi() {
        if (isHdmiRegistered) {
            return;
        }
        isHdmiRegistered = true;

        IntentFilter filter = new IntentFilter();
//        filter.addAction(ACTION_HDMI_PLUGGED);
        filter.addAction(ACTION_DP_PLUGGED);
        if (getActivity() != null) {
            getActivity().registerReceiver(hdmiReceiver, filter);
        }

    }

    private void unregisterHdmi() {
        if (!isHdmiRegistered) {
            return;
        }
        isHdmiRegistered = false;
        if (getActivity() != null) {
            getActivity().unregisterReceiver(hdmiReceiver);
        }
    }

    private BroadcastReceiver hdmiReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            DebugLog.e("intent = " + intent);
            DebugLog.e("action = " + intent.getAction());
            String action = intent.getAction();
            boolean plugged = false;
            if (action == null) {
                return;
            }

            if (action.equals(ACTION_DP_PLUGGED)) {
                plugged = intent.getBooleanExtra(EXTRA_DP_PLUGGED_STATE, false);
                if (plugged) {
                    setTxtStatusPlugged(txtStatusHdmi);
                }
//            } else if (action.equals(ACTION_HDMI_PLUGGED)) {
//                plugged = intent.getBooleanExtra(EXTRA_HDMI_PLUGGED_STATE, false);
            }
            updateTxtInfo("action = " + action + ", plugged = " + plugged);

        }
    };

    /////////////
    // ethernet
    private boolean isEthernetRegistered = false;

    private void registerEthernet() {
        if (isEthernetRegistered) {
            return;
        }
        isEthernetRegistered = true;

        ConnectivityManager cm = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkRequest request = new NetworkRequest.Builder().addTransportType(NetworkCapabilities.TRANSPORT_ETHERNET).build();
        cm.registerNetworkCallback(request, ethernetCallback);
    }

    private void unregisterEthernet() {
        if (!isEthernetRegistered) {
            return;
        }
        isEthernetRegistered = false;

        ConnectivityManager cm = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);

        cm.unregisterNetworkCallback(ethernetCallback);

    }

    private ConnectivityManager.NetworkCallback ethernetCallback = new ConnectivityManager.NetworkCallback() {

        @Override
        public void onCapabilitiesChanged(Network network, NetworkCapabilities networkCapabilities) {
            super.onCapabilitiesChanged(network, networkCapabilities);
            if (networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
                updateTxtInfo("onCapabilitiesChanged: 网络类型为wifi");
            } else if (networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) {
                updateTxtInfo("onCapabilitiesChanged: 蜂窝网络");
            } else if (networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET)) {
                setTxtStatusPlugged(txtStatusEthernet);
                updateTxtInfo("onCapabilitiesChanged:以太网络");
            } else {
                updateTxtInfo("onCapabilitiesChanged: 其他网络");
            }
        }
    };

    //////
    // U storage
    private SDCardInfo sdCardInfo;
    private void registerUStorage() {
        if (sdCardInfo == null) {
            sdCardInfo = new SDCardInfo(mContext);
        }
        sdCardInfo.startMonitor();
        sdCardInfo.setOnVolumeStateChangedListener(onVolumeStateChangedListener);

    }
    private void unregisterUStorage() {
        if (sdCardInfo != null) {
            sdCardInfo.stopMonitor();
            sdCardInfo = null;
        }
    }

    private SDCardInfo.OnVolumeStateChangedListener onVolumeStateChangedListener =
            new SDCardInfo.OnVolumeStateChangedListener() {
                @Override
                public void onVolumeStateChangedListener(SDCardInfo sdCardInfo, String action, Uri data) {
                    updateTxtInfo("action = " + action + ", " + data.getPath());

                    if (action == null || data.getPath() == null) {
                        return;
                    }

                    if (action.equals(Intent.ACTION_MEDIA_MOUNTED) && data.getPath().contains(U_STORAGE_PATH_NAME)) {
                        setTxtStatusPlugged(txtStatusUStorage);
                    }

                    List<StorageVolume> storageVolumeList = sdCardInfo.getPublicVolumesExceptSD();
                    for (StorageVolume vol : storageVolumeList) {
                        String volumePath = sdCardInfo.getVolumePath(vol);
                        updateTxtInfo("volumePath = " + volumePath);
                        if (volumePath != null && data.toString().contains(volumePath)) {
                            String volInfo = ("vol state = " + vol.getState() + ", desc = " + vol.getDescription(mContext) + ", isPrimary = " + vol.isPrimary());
                            updateTxtInfo(volInfo);
                            break;
                        }
                    }
                }
            };


    private void updateTxtInfo(String info) {
        String sInfo = txtInfo.getText().toString();
        if (sInfo.length() > 1024) {
            sInfo = info;
        } else {
            sInfo += "\n" + info;
        }
        txtInfo.setText(sInfo);

    }
}
